package service;

import java.sql.Connection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import util.BeanFactoryUtil;
import base.BaseIbatis3Dao;
import bean.Persion;
import dao.PersionDao;

@Service
@Transactional
public class PersionService {

	private PersionDao persionDao;

	public void setPersionDao(PersionDao persionDao) {
		this.persionDao = persionDao;
	}

	//可以同时使用多个DAO,多个DAO在一个事物中
	@Autowired
	@Qualifier("persionDao")//指定名称注入
	private PersionDao dao;

	public void setDao(PersionDao dao) {
		this.dao = dao;
	}

	public void execute() throws Exception {
		Persion persion = new Persion();
		persion.setId(BaseIbatis3Dao.getUUID());
		persion.setName("nameaaaaaaaaa");
		dao.save(persion);
		// 可以手工提交
		Connection conn = persionDao.getSqlSessionTemplate().getConnection();
		conn.commit();

		Persion persion2 = new Persion();
		persion2.setId(BaseIbatis3Dao.getUUID());
		persion2.setName("nameabbbbbb");
		persionDao.save(persion2);
		throw new RuntimeException("错误@!!");//这里抛出运行期异常后事物回滚
	}

	public static void main(String[] args) {
		PersionService service = (PersionService) BeanFactoryUtil.getBean("persionService");
		try {
			service.execute();
			System.out.println("OK");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
